package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.SetmealService;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huhanzhao
 * @create 2022-11-11-20:02
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Override
    public void subNumber(ShoppingCart shoppingCart) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        if (shoppingCart.getDishId() == null){
            //减少套餐
            //查套餐数量，小于2就删除，大于等于2就数量减一
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
            ShoppingCart cart = shoppingCartService.getOne(queryWrapper);
            Integer number = cart.getNumber();
            if (number == 1){
                shoppingCartService.removeById(cart.getId());
            }else{
                cart.setNumber(number - 1);
                shoppingCartService.updateById(cart);
            }

        }else {
            //减少dish
            //查菜品数量，小于2就删除，大于等于2就数量减一
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
            ShoppingCart cart = shoppingCartService.getOne(queryWrapper);
            Integer number = cart.getNumber();
            if (number == 1){
                shoppingCartService.removeById(cart.getId());
            }else{
                cart.setNumber(number - 1);
                shoppingCartService.updateById(cart);
            }
        }
    }
}
